package com.ddc.study.net;

import com.ddc.study.util.Log;

import java.io.IOException;
import java.util.Locale;

import androidx.annotation.NonNull;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created on 2018/5/18.
 *
 * @author lshun
 * @version 1.0
 */
public class LogInterceptor implements Interceptor {
    private static final String TAG = "LogInterceptor";

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();//请求发起的时间
        Log.w(TAG, String.format("request -> %s on %s -> %s",
                request.url(), chain.connection(), request.headers()));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();//收到响应的时间

        //这里不能直接使用response.body().string()的方式输出日志
        //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
        //个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(20 * 1024 * 1024);
        Log.w(TAG, String.format(Locale.getDefault(), "response -> %s %.1fms\n%s %n %s\n",
                response.request().url(),
                (t2 - t1) / 1e6d,
                response.headers(),
                responseBody.string()));
        return response;
    }
}
